/**
 * 添加备件
 */
function addSpareparts() {
    if (!app.getNetworkState()) {
        app.toast("无网络")
        return
    }

    var serviceNo = h('#serviceNo').html(); // 服务编号
    var portType = h('#portType').val(); // 报告类型（备件类型）
    var annexHelpId = h('#helpId').val(); // 备件辅助id
    var helpId = h('#phoneHelpId').val(); // 报告辅助id
    var pid = h('#pid').val(); // 备件编号
    var partNumber = h('#partNumber').val(); // 备件号
    var qtyCount = h('#qtyCount').val(); // 备件数量
	var qtyCountMax = h('#qtyCount').attr('max'); // 备件最大数量
	var qtyCountMin = h('#qtyCount').attr('min'); // 备件最小数量
    var partName = h('#partName').val(); // 备件名称
    var partType = h('#partType').val(); // 备件类型值
    var partTypeName = h('#partTypeName').html(); // 备件类型名
    var partSerialNumber = h('#partSerialNumber').val(); // 备件序列号
    var damageSerialNumber = h('#damageSerialNumber').val(); // 坏件序列号
    var price = h('#price').val() || 0; // Price单价
    var totalprice = h('#totalprice').val(); // Price总价
    var changeRemark = h('#changeRemark').val(); // 备注
    var isOutWarranty = h('#isOutWarranty').val(); // 坏件是否还库
    var statusChange = h('#statusChange').val(); // 备件状态变更说明
    var isWarranty = h('#isWarranty').val(); // 保内 保外
    var loanNumber = h('#loanNumber').val();
    var remark = h('#remark').val();

    if (!partNumber) {
        app.toast("请选择备件");
        return
    }
    if (!qtyCount) {
        app.toast("请输入备件数量");
        return
    }
    if (qtyCount < 1) {
        app.toast("请输入正确的备件数量");
        return
    }
	if (qtyCount > qtyCountMax ) {
		app.toast("备件数量不能大于库存的备件数量")
		return
	}
    if (!partName) {
        app.toast("备件名称不能为空");
        return
    }
    if (!partType) {
        app.toast("请选择备件类型");
        return
    }
    /* if (!price) {
        app.toast("请输入Price单价");
        return
    } */

    // 如果是保外服务且坏件是否还库选否 则非必填
    /*if (isWarranty == '保外') {
        if (!isOutWarranty) {
            app.toast("请选择坏件是否还库");
            return
        }
        if (isOutWarranty == '1') {
            if (!damageSerialNumber && SNPartsList.indexOf(partNumber) >= 0) {
                app.toast("请输入坏件序列号");
                return
            }
            if (!statusChange) {
                app.toast("请选择备件状态变更说明");
                return
            }
            if (statusChange == '4') {
                if (changeRemark == undefined || changeRemark == '') {
                    app.toast("请填写备件状态变更说明");
                    return
                }
            }
            var picsize = h('#picsize').val()
            if (damageSerialNumber && (!picsize || picsize <= 0) && PicPartsList.indexOf(partNumber) >= 0) {
                app.toast("请添加坏件图片");
                return
            }
        }
    } else {
        if (!isOutWarranty) {
            app.toast("请选择坏件是否还库");
            return
        }
        if (!damageSerialNumber && SNPartsList.indexOf(partNumber) >= 0) {
            app.toast("请输入坏件序列号");
            return
        }
        if (isOutWarranty == '1') {

            if (!statusChange) {
                app.toast("请选择备件状态变更说明");
                return
            }
            if (statusChange == '4') {
                if (changeRemark == undefined || changeRemark == '') {
                    app.toast("请填写备件状态变更说明");
                    return
                }
            }
        }
        var picsize = h('#picsize').val()
        if ((!picsize || picsize <= 0) && PicPartsList.indexOf(partNumber) >= 0) {
            app.toast("请添加坏件图片");
            return
        }
    }*/

    if (isWarranty == '保外') {
        if (!isOutWarranty) {
            app.toast("请选择坏件是否还库");
            return
        }

        if (isOutWarranty == '1') {
            if (!statusChange) {
                app.toast("请选择备件状态变更说明");
                return
            }
            if (statusChange == '4') {
                if (changeRemark == undefined || changeRemark == '') {
                    app.toast("请填写备件状态变更说明");
                    return
                }
            }
        }
    }

    if (isWarranty == '保外' && isOutWarranty != '1') {
        // TODO 保外  是否还库 =否  不做校验 ，其他都校验
    }
    else {

        if (!damageSerialNumber && SNPartsList.indexOf(partNumber) >=0) {
            app.toast("请输入坏件序列号");
            return
        }

        var picsize = h('#picsize').val()
        if ((!picsize || picsize <= 0)  && PicPartsList.indexOf(partNumber) >=0) {
            app.toast("请添加坏件图片");
            return
        }
    }

    var params = {
        serviceNo,
        enginnerId: app.getUser().enginnerId,
        portType,
        partNumber,
        partSerialNumber,
        partName,
        qtyCount,
        price,
        totalprice,
        partType,
        partTypeName,
        damageSerialNumber,
        isOutWarranty,
        statusChange,
        changeRemark,
        pid: pid,
        helpId,
        annexHelpId,
        loanNumber,
        remark
    }
    app.showWaiting("正在保存...")
    ajaxPost(BASE_URL + 'cc/report/port/addReportPort', params, function (data) {
        app.closeWaiting()
        if (data.code === 200) {
            app.toast("保存成功")
            mui.back()
        } else {
            app.toast()
        }
    }, function (errormsg) {
        app.closeWaiting()
        app.toast(errormsg)
    })

}

var needDelId;
var needDelObj;
var sendPid;

function fixedDel() {
    mui("#popover").popover('toggle', document.getElementById("div"));
    app.showWaiting('删除中...')
    ajaxGet(BASE_URL + "cc/report/port/removeReportPort", {
        reportPortId: needDelId,
        enginnerId: app.getUser().enginnerId,
        pid: sendPid
    }, function (data) {
        app.closeWaiting()
        if (data.code === 200) {
            app.toast('删除成功')
            h(needDelObj).parent().parent().remove()
        } else {
            app.toast(data.msg)
        }
    }, function (errorMsg) {
        app.closeWaiting()
        app.toast(errorMsg)
    });
}

function closePopover() {
    mui("#popover").popover('toggle', document.getElementById("div"));
}

/**
 * 删除备件
 */
function deleteSpareparts(_this, reportPortId, pid) {
    needDelId = reportPortId;
    sendPid = pid;
    needDelObj = _this;
    mui("#popover").popover('toggle', document.getElementById("div"));
}

// 坏件图片 图片信息列表
function picList(_this, id) {
    var helpId = h("#" + id).attr("annexHelpId");
    app.jumpTo('/view/service/picture/list.html', 'view/service/picture/list.html', {
        helpId: helpId,
        serviceNo: h('#serviceNo').val(),
		submitStatus: submitStatus
    });
}

/**
 * 备件列表
 */
function listSpareparts(serviceNo, helpId, type) {
    app.showWaiting()
    ajaxGet(BASE_URL + 'cc/report/port/selectReportPorts', {
        serviceNo,
        helpId,
        type
    }, function (data) {
        app.closeWaiting()
        if (data.code === 200) {
            if (data.data && data.data.length > 0) {
                var str = ``
                for (var i = 0; i < data.data.length; i++) {
                    str += `
						<div class="item" annexHelpId="${data.data[i].annexHelpId}" helpId="${data.data[i].helpId}" id="${data.data[i].id}" pid="${data.data[i].pid}" portType="${data.data[i].portType}">
							<p class="bar">
								<span class="number">
									${data.data[i].partNumber || ''}
									<img src="../../../../../images/icon_204.png" />
								</span>
                                <span class="del" onclick="deleteSpareparts(this, ${data.data[i].id},${data.data[i].pid})">删除</span>
								<span ${ data.data[i].annexList.length > 0? 'class="tupian"' : 'class="tupian mui-plus-hidden' } onclick="picList(this, ${data.data[i].id})">坏件图片 &nbsp;</span>
							</p>
							<div class="text">
								<span class="text-title">借货单号：</span>
								<span class="text-value">${data.data[i].loanNumber || ''}</span>
							</div>
							<div class="text">
								<span class="text-title">备件名称：</span>
								<span class="text-value">${data.data[i].partName || ''}</span>
							</div>
							<div class="text">
								<span class="text-title">备件序列号：</span>
								<span class="text-value">${data.data[i].partSerialNumber || ''}</span>
							</div>
							<div class="text">
								<span class="text-title">坏件序列号：</span>
								<span class="text-value">${data.data[i].damageSerialNumber || ''}</span>
							</div>
							<div class="attribute autoHeight" style="margin-top: 10px;">
								<p>数量：<span>${data.data[i].qtyCount || ''}</span></p>
								<p>单价：<span>${data.data[i].price || 0}</span></p>
								<p>总价：<span>${data.data[i].totalprice || 0}</span></p>
							</div>
						</div>
					`
                }
                h('#itemBox').html(str);
                if (submitStatus == '1') {
                    h('.del').hide()
                }
            } else {
                noData()
            }
        } else {
            noData()
            app.toast(data.msg)
        }
    }, function () {
        app.closeWaiting()
        noData()
        app.toast(errorMsg)
    })
}

function noData() {
    html = '<div class="nodata">—— 暂无数据 ——</div>';
    h("#itemBox").html(html);
}

//图片清单
function getPicPartsList() {
    ajaxGetJson(BASE_URL + 'cc/spareParts/consumablesList', {
        tableName: 'PicPartsList',
        engineerId: app.getUser().enginnerId
    }, function (data) {
        var dataObj = JSON.parse(data);
        PicPartsList = JSON.stringify(dataObj.record);
    });
}

//序列号清单
function getSNPartsList() {
    ajaxGetJson(BASE_URL + 'cc/spareParts/consumablesList', {
        tableName: 'SNPartsList',
        engineerId: app.getUser().enginnerId
    }, function (data) {
        var dataObj = JSON.parse(data);
        SNPartsList = JSON.stringify(dataObj.record);
    });
}
